package com.sec.etech.ism.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sec.etech.common.constant.DBConstant;
import com.sec.etech.common.util.RequestHolder;
import com.sec.etech.ism.constant.SignatureConstant;
import com.sec.etech.ism.service.IsmMethodService;
import com.sec.etech.ism.service.IsmTaskService;
import com.sec.etech.ism.util.IsmStringUtil;
import com.sec.etech.process.service.SppRelFileService;
import com.sec.etech.process.service.SppRelSamService;
import com.sec.etech.process.service.SppRelToolService;
import com.sec.etech.sys.util.DbUtil;
import lombok.extern.slf4j.Slf4j;
import org.openbpm.base.api.exception.BusinessMessage;
import org.openbpm.base.core.util.StringUtil;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class IsmGetOperationCardServiceImpl implements IsmMethodService {
    @Resource
    SppRelFileService sppRelFileService;
    @Resource
    SppRelSamService sppRelSamService;
    @Resource
    SppRelToolService sppRelToolService;
    @Resource
    IsmTaskService ismTaskService;

    public IsmGetOperationCardServiceImpl(){}

    @Override
    public JSONObject call(String sysCode, String serviceCode, JSONObject businessParams) throws Exception{
        JSONObject result = new JSONObject();
        List<JSONObject> opCardList = this.checkAndGetData(businessParams);
        List<JSONObject> dataList = new ArrayList<>(opCardList.size());
        for(JSONObject object:opCardList){
            JSONObject routeCardObj = this.getOperationCard(object);
            dataList.add(routeCardObj);
        }
        ismTaskService.deleteTaskByParams(sysCode, serviceCode, serviceCode, null, businessParams.getString(SignatureConstant.INPUT_PARAMS));
        result.put("flag", "success");
        result.put("data", dataList);
        return result;
    }
    //入参检查
    private List<JSONObject> checkAndGetData(JSONObject busParams) throws BusinessMessage{
        if(StringUtil.isEmpty(busParams.getJSONObject(SignatureConstant.INPUT_PARAMS).getString("opCardList"))){
            throw new BusinessMessage("请求中缺少opCardList参数，请检查！");
        }
        List<JSONObject> opCardList = (List<JSONObject>) busParams
                .getJSONObject(SignatureConstant.INPUT_PARAMS).get("opCardList");
        if(opCardList.size()==0){
            throw new BusinessMessage("请求中缺少opCardList参数，请检查！");
        }
        for(JSONObject object: opCardList){
            if(!object.containsKey("operation_card") || StringUtil.isEmpty(object.getString("operation_card"))){
                throw new BusinessMessage("请求参数opCardList（列表）中缺少operation_card参数，请检查！");
            }else if(StringUtil.isEmpty(object.getString("operation_card"))){
                throw new BusinessMessage("请求参数opCardList（列表）中存在operation_card参数为空，请检查！");
            }
        }
        return opCardList;
    }
    //根据工序卡号获取工序卡信息
    private JSONObject getOperationCard(JSONObject object){
        JdbcTemplate slaveJdbcTemplate = DbUtil.getJdbcTemplate(DBConstant.ETECH_SLAVE);
        String operationCard = object.getString("operation_card");
        //查找工序卡信息
        String sql = "select t1.op_rev_id, t1.statusid, t1.op_name, t2.serial_num route_serial," +
                "t3.componentnum,t3.componentname,t4.partsnum,t4.partsname,t5.`name` op_type " +
                "from spp_operation_rev t1 left join spp_route_rev t2 on t2.route_rev_id=t1.route_rev_id " +
                "left join prod_component t3 on t1.plantaskid=t3.componentid left join prod_parts t4 on t4.partsid=t1.partsid " +
                "left join spp_operation_z_type t5 on t5.op_type_id=t1.op_type_id " +
                "where t1.curr_ver=1 and t1.active=1 and t1.serial_num=?";
        List<Map<String,Object>> opList = slaveJdbcTemplate.queryForList(sql, operationCard);
        if(opList==null || opList.size()==0){
            return new JSONObject();
        }
        JSONObject dataObj = new JSONObject();
        if(StringUtil.isNotEmpty(opList.get(0).get("partsnum"))) {
            dataObj.put("partsnum", IsmStringUtil.getStrNullToEmpty(opList.get(0).get("partsnum")));
            dataObj.put("partsname", IsmStringUtil.getStrNullToEmpty(opList.get(0).get("partsname")));
        }else {
            dataObj.put("componentnum", IsmStringUtil.getStrNullToEmpty(opList.get(0).get("componentnum")));
            dataObj.put("componentname", IsmStringUtil.getStrNullToEmpty(opList.get(0).get("componentname")));
        }
        dataObj.put("route_serial", opList.get(0).get("route_serial"));//关联路线卡号
        dataObj.put("operation_card", operationCard);//工序卡编号
        dataObj.put("operation_name", opList.get(0).get("op_name"));//工序卡名称
        dataObj.put("operation_type", opList.get(0).get("op_type"));//工艺类型
        Integer statusId = opList.get(0).get("statusid")!=null ? (Integer) opList.get(0).get("statusid") : null;
        if(statusId==null || statusId==1){
            dataObj.put("status", "编制中");
        }else if(statusId==2){
            dataObj.put("status", "已完成");
        }else if(statusId==3){
            dataObj.put("status", "已入库");
        }

        Long opRevId = (Long) opList.get(0).get("op_rev_id");
        //获取组装工步图信息
        List<Map<String, Object>> files = sppRelFileService.getAttachments(opRevId, 2, true);
        List<JSONObject> fileList = new ArrayList<>();
        if(files!=null && files.size()>0) {
            String preUrl = RequestHolder.getUrl() + "/sys/sysFile/preview.html?audience=drawing&fileId=";
            for(Map<String, Object> map:files){
                JSONObject fileObj = new JSONObject();
                fileObj.put("file_name", map.get("name_"));
                fileObj.put("url", preUrl + map.get("fileid").toString());
                fileList.add(fileObj);
            }
            dataObj.put("fileList", fileList);
        }
        dataObj.put("fileList", fileList);
        //获取工步信息
        sql = "select t1.op_step_id,t1.step_no,t2.`code` worktype_name,t3.`code` workcenter_code,t1.step_content,t1.remark " +
                "from spp_operation_step t1 left join proc_process_z_worktype t2 on t1.worktype_id=t2.worktype_id " +
                "left join proc_process_z_work_center t3 on t1.workcenter_id=t3.workcenter_id where t1.active=1 and t1.op_rev_id=?";
        List<Map<String,Object>> opStepObjList = slaveJdbcTemplate.queryForList(sql, opRevId);
        if(opStepObjList==null || opStepObjList.size()==0){
            dataObj.put("stepList", new ArrayList<>());
            return dataObj;
        }
        List<JSONObject> opStepList = new ArrayList<>();
        for(Map<String,Object> opStepMap: opStepObjList){
            JSONObject opStepObj = new JSONObject();
            opStepObj.put("step_no", opStepMap.get("step_no"));//工步
            opStepObj.put("worktype_name", IsmStringUtil.getStrNullToEmpty(opStepMap.get("worktype_name")));//设备工种
            opStepObj.put("workcenter_code", IsmStringUtil.getStrNullToEmpty(opStepMap.get("workcenter_code")));//工作中心
            opStepObj.put("step_content", IsmStringUtil.getStrNullToEmpty(opStepMap.get("step_content")));//工序描述
            opStepObj.put("remark", IsmStringUtil.getStrNullToEmpty(opStepMap.get("remark")));//备注

            Long opStepId = Long.parseLong(opStepMap.get("op_step_id").toString());
            //查询组装标准信息
            List<Map<String, Object>> sames = sppRelSamService.getRefSams(opRevId, 2, opStepId);
            List<JSONObject> samList = new ArrayList<>();
            if(sames!=null && sames.size()>0) {
                for(Map<String, Object> samMap:sames){
                    JSONObject samObj = new JSONObject();
                    samObj.put("sam_code", samMap.get("samCode"));
                    samObj.put("sam_name", samMap.get("samName"));
                    samList.add(samObj);
                }
            }
            opStepObj.put("samList", samList);
            //查询组装工装信息
            List<Map<String, Object>> tools = sppRelToolService.getRefTools(opRevId, 2, opStepId);
            List<JSONObject> toolList = new ArrayList<>();
            if(tools!=null && tools.size()>0) {
                for(Map<String, Object> toolMap:tools){
                    JSONObject toolObj = new JSONObject();
                    toolObj.put("tooling_num", toolMap.get("toolingNum"));
                    toolObj.put("tooling_name", toolMap.get("toolingName"));
                    toolList.add(toolObj);
                }
            }
            opStepObj.put("toolList", toolList);
            opStepList.add(opStepObj);
        }
        dataObj.put("stepList", opStepList);
        return dataObj;
    }

    @Override
    public String methodName(){
        return "getOperationCard";
    }
}
